<!--
 * @Author: your name
 * @Date: 2021-03-15 20:53:56
 * @LastEditTime: 2021-03-15 20:56:17
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edi
 * @FilePath: \study\js\面试题\数组计算.html
-->
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Document</title>
    </head>

    <body>
        <p>订阅模式</p>
        <button id="box">点击</button>
        <button id="box1">点击1</button>
        <script>
            class Subject {
                constructor(name, state) {
                    this.name = name;
                    this.state = '正常' || state;
                    this.observerList = [];
                }
                attach(observer) {
                    this.observerList.push(observer);
                }
                setState(newState) {
                    this.state = newState;
                    this.observerList.forEach((element) => {
                        element.update(newState);
                    });
                }
            }
            class Observer {
                constructor(obName) {
                    this.obName = obName;
                }
                update(newState) {
                    console.log(this.obName + newState);
                }
            }

            let sub = new Subject('宝宝', '笑了');
            let ob1 = new Observer('爸爸');
            let ob2 = new Observer('妈妈');
            // 添加观察者
            sub.attach(ob1);
            sub.attach(ob2);

            sub.setState('哭了');
        </script>
    </body>
</html>
